using AutoMapper;
using B.S.BaseData.Api.Write.Applicantion.Command.OrderCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using WorkOrder.Domain;

namespace B.S.BaseData.Api.Write.Applicantion.CommandHandler.OrderCommandHandler
{
    /// <summary>
    /// 删除问诊单处理器（软删除）
    /// </summary>
    public class DeleteConsultationOrderHandler : IRequestHandler<DeleteConsultationOrderCommand, APIResult<bool>>
    {
        private readonly BaseDbContext _context;
        private readonly IMapper _mapper;

        public DeleteConsultationOrderHandler(BaseDbContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public async Task<APIResult<bool>> Handle(DeleteConsultationOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var order = await _context.ConsultationOrders
                    .FirstOrDefaultAsync(c => c.OrderNumber == request.OrderNumber && !c.IsDelete, cancellationToken);

                if (order == null)
                {
                    return new APIResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "未找到指定的问诊单或该订单已被删除",
                        Data = false
                    };
                }

                // 检查订单状态，某些状态下不允许删除
                if (order.OrderStatus == "进行中")
                {
                    return new APIResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "进行中的问诊单不能删除",
                        Data = false
                    };
                }

                // 执行软删除
                order.IsDelete = true;
 
                _context.ConsultationOrders.Update(order);
                await _context.SaveChangesAsync(cancellationToken);

                return new APIResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = "删除成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                return new APIResult<bool>
                {
                    Code = ApiEnum.Fail,
                    Msg = $"删除失败: {ex.Message}",
                    Data = false
                };
            }
        }
    }

    /// <summary>
    /// 批量删除问诊单处理器（软删除）
    /// </summary>
    public class BatchDeleteConsultationOrderHandler : IRequestHandler<BatchDeleteConsultationOrderCommand, APIResult<bool>>
    {
        private readonly BaseDbContext _context;
        private readonly IMapper _mapper;

        public BatchDeleteConsultationOrderHandler(BaseDbContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public async Task<APIResult<bool>> Handle(BatchDeleteConsultationOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (request.OrderNumbers == null || !request.OrderNumbers.Any())
                {
                    return new APIResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "请选择要删除的问诊单",
                        Data = false
                    };
                }

                var orders = await _context.ConsultationOrders
                    .Where(c => request.OrderNumbers.Contains(c.OrderNumber) && !c.IsDelete)
                    .ToListAsync(cancellationToken);

                if (!orders.Any())
                {
                    return new APIResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "未找到指定的问诊单或订单已被删除",
                        Data = false
                    };
                }

                // 检查是否有进行中的订单
                var inProgressOrders = orders.Where(o => o.OrderStatus == "进行中").ToList();
                if (inProgressOrders.Any())
                {
                    var inProgressOrderNumbers = string.Join(", ", inProgressOrders.Select(o => o.OrderNumber));
                    return new APIResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = $"以下进行中的问诊单不能删除: {inProgressOrderNumbers}",
                        Data = false
                    };
                }

                // 执行批量软删除
                foreach (var order in orders)
                {
                    order.IsDelete = true;
        
                }

                _context.ConsultationOrders.UpdateRange(orders);

                await _context.SaveChangesAsync(cancellationToken);

                return new APIResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = $"成功删除 {orders.Count} 个问诊单",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                return new APIResult<bool>
                {
                    Code = ApiEnum.Fail,
                    Msg = $"批量删除失败: {ex.Message}",
                    Data = false
                };
            }
        }
    }
}
